package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.TemplateFieldEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.model.ContractEditFileModel;
import com.xbongbong.paas.model.ContractTemplateBaseModel;
import com.xbongbong.pro.onlineEditor.OnlineEditorMap4ExportPojo;
import com.xbongbong.pro.onlineEditor.TemplateFieldValuePojo;
import com.xbongbong.saas.constant.OnlineEditorConstant;
import com.xbongbong.saas.domain.entity.ContractEditFileEntity;
import com.xbongbong.saas.domain.entity.ContractTemplateBaseEntity;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author: yingjf
 * @date: 2023/3/14 11:07
 * @description: 在线编辑器帮助类
 */
@Slf4j
@AllArgsConstructor
@Component("onlineEditorHelp")
public class OnlineEditorHelp {
    private ContractEditFileModel contractEditFileModel;
    private ContractTemplateBaseModel contractTemplateBaseModel;

    /**
     * 封装参数  导出使用
     * date: 2023/3/14 13:50
     *
     * @param corpid
     * @param formDataEntityExts
     * @param explainList
     * @author yingjf
     */
    public OnlineEditorMap4ExportPojo getOnlineEditorMap4Export(String corpid, List<PaasFormDataEntityExt>
            formDataEntityExts, List<FieldAttrEntity> explainList) {
        OnlineEditorMap4ExportPojo onlineEditorMap4ExportPojo = new OnlineEditorMap4ExportPojo();
        try {
            if (formDataEntityExts == null || explainList == null) {
                return onlineEditorMap4ExportPojo;
            }

            String templateFieldAttr = null;
            for (FieldAttrEntity temp : explainList) {
                Integer fieldType = temp.getFieldType();
                if (Objects.equals(fieldType, FieldTypeEnum.TEMPLATE_FIELD.getType())) {
                    templateFieldAttr = temp.getAttr();
                    onlineEditorMap4ExportPojo.setTemplateFieldAttr(templateFieldAttr);
                    break;
                }
            }
            Set<Long> baseContractIdSet = new HashSet<>();
            List<Map<String, String>> fileList = new ArrayList<>();
            for (PaasFormDataEntityExt paasFormDataEntityExt : formDataEntityExts) {
                JSONObject data = paasFormDataEntityExt.getData();
                JSONObject jsonObject = data.getJSONObject(templateFieldAttr);
                Long baseContractId = jsonObject.getLong(OnlineEditorConstant.BASE_CONTRACT_ID);
                String contractEditFileId = jsonObject.getString(OnlineEditorConstant.CONTRACT_EDIT_FILE_ID);
                String contractEditFileVersion = jsonObject.getString(OnlineEditorConstant.CONTRACT_EDIT_FILE_VERSION);
                baseContractIdSet.add(baseContractId);
                Map<String, String> tempMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                tempMap.put("fileId", contractEditFileId);
                tempMap.put("fileVersion", contractEditFileVersion);
                fileList.add(tempMap);
            }
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", corpid);
            params.put("idIn", baseContractIdSet);
            List<ContractTemplateBaseEntity> contractTemplateBaseEntityList = contractTemplateBaseModel.findEntities(params);
            if (contractTemplateBaseEntityList != null) {
                Map<Long, String> templateNameMap = new HashMap<>();
                contractTemplateBaseEntityList.forEach(item -> {
                    templateNameMap.put(item.getId(), item.getTemplateName());
                });
                onlineEditorMap4ExportPojo.setTemplateNameMap(templateNameMap);
            }


            List<ContractEditFileEntity> contractEditFileEntityList = contractEditFileModel.getByFileIdAndFileVersion(corpid, fileList);
            if (contractEditFileEntityList != null) {
                Map<String, String> fileMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                contractEditFileEntityList.forEach(item -> {
                    String key = item.getFileId() + item.getFileVersion();
                    fileMap.put(key, item.getFileUrl());
                });
                onlineEditorMap4ExportPojo.setFileMap(fileMap);
            }
        } catch (Exception e) {
            log.error("com.xbongbong.paas.help.OnlineEditorHelp.getOnlineEditorMap4Export", e);
        }
        return onlineEditorMap4ExportPojo;
    }

    /**
     * 处理下导出data里的模板字段的value格式
     * date: 2023/3/14 13:59
     *
     * @param onlineEditorMap4ExportPojo
     * @param formDataObj
     * @author yingjf
     */
    public void packageData4Export(OnlineEditorMap4ExportPojo onlineEditorMap4ExportPojo, JSONObject formDataObj) {
        String templateFieldAttr = onlineEditorMap4ExportPojo.getTemplateFieldAttr();
        Map<String, String> fileMap = onlineEditorMap4ExportPojo.getFileMap();
        Map<Long, String> templateNameMap = onlineEditorMap4ExportPojo.getTemplateNameMap();

        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        list.add(map);

        try {
            if (formDataObj == null) {
                return;
            }

            JSONObject templateFieldValue = formDataObj.getJSONObject(templateFieldAttr);
            if (templateFieldValue == null) {
                return;
            }
            Long baseContractId = templateFieldValue.getLong(OnlineEditorConstant.BASE_CONTRACT_ID);
            String contractEditFileId = templateFieldValue.getString(OnlineEditorConstant.CONTRACT_EDIT_FILE_ID);
            String contractEditFileVersion = templateFieldValue.getString(OnlineEditorConstant.CONTRACT_EDIT_FILE_VERSION);

            if (fileMap != null) {
                String fileUrl = fileMap.get(contractEditFileId + contractEditFileVersion);
                map.put(TemplateFieldEnum.FILE.getAlias(), fileUrl);
            }
            if (templateNameMap != null) {
                String contractName = templateNameMap.get(baseContractId);
                map.put(TemplateFieldEnum.TEMPLATE_NAME.getAlias(), contractName);
            }
        } catch (Exception e) {
            map.put(TemplateFieldEnum.FILE.getAlias(), "");
            map.put(TemplateFieldEnum.TEMPLATE_NAME.getAlias(), "");
            log.error("com.xbongbong.paas.help.OnlineEditorHelp.packageData4Export", e);
        }
        formDataObj.put(templateFieldAttr, list);
    }

    /**
     * 解析模板字段值
     * date: 2023/3/15 08:42
     *
     * @param jsonStr
     * @author yingjf
     */
    public TemplateFieldValuePojo analysisTemplateField(String corpid, String jsonStr) {
        TemplateFieldValuePojo templateFieldValuePojo = JSONObject.parseObject(jsonStr, TemplateFieldValuePojo.class);
        Long base_contract_id = templateFieldValuePojo.getBase_contract_id();
        String contract_edit_file_id = templateFieldValuePojo.getContract_edit_file_id();
        Integer contract_edit_file_version = templateFieldValuePojo.getContract_edit_file_version();

        if (base_contract_id != null) {
            ContractTemplateBaseEntity contractTemplateBaseEntity = contractTemplateBaseModel.getByKey(base_contract_id, corpid);
            if (contractTemplateBaseEntity != null) {
                templateFieldValuePojo.setBase_contract_name(contractTemplateBaseEntity.getTemplateName());
            }
        }
        if (contract_edit_file_id != null && contract_edit_file_version != null) {
            ContractEditFileEntity contractEditFileEntity = contractEditFileModel.getOneByFileIdAndFileVersion(corpid, contract_edit_file_id, contract_edit_file_version);
            if (contractEditFileEntity != null) {
                templateFieldValuePojo.setFile_url(contractEditFileEntity.getFileUrl());
                templateFieldValuePojo.setFile_name(contractEditFileEntity.getFileName());
                templateFieldValuePojo.setFile_ext(contractEditFileEntity.getFileExt());
                templateFieldValuePojo.setFile_size(contractEditFileEntity.getFileSize());
            }
        }
        return templateFieldValuePojo;
    }


}
